<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Sample as SampleModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Log as LogModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 工程样品控制器
 * @package app\admin\controller
 */
class Sample extends Admin
{

    /**
     * 样品管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function order()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $order_sn = '';
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.order_sn')$order_sn = trim($v[2],'%');
            }
        }
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,cc.create_time as contract_time')
            ->where($map)
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->leftJoin('mill_order_contract cc','cc.order_id=o.order_pid')
            ->group('o.order_pid')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $v['batch'] = Db::name('mill_order')->where(['order_pid'=>$v['order_pid'],'archives_status'=>2])->count();

                return $v;
            })
        ;

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('样品管理') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程编号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.sales', '销售经理', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['order_sn', '工程编号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                //['batch','批次数量'],
                ['client_id','销售经理',ClientModel::getSalesList()],
                //['money_str', '订金'],
                ['status_verify_uid','审核人',UserModel::getList()],
                ['back', '内勤'],
                ['note', '备注','popover'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('index',['title' => '查看样品','href' => url('mill/sample/index',['order_id' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->replaceRightButton(['status'=>['<>','1']],'','archives')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 样品列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $order_id = input('order_id');
        // 获取查询条件
        $map = $this->getMap();
        if($order_id)$map[] = ['s.order_id','=',$order_id];

        // 数据列表
        $data_list = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*')
            ->where($map)
            //->leftJoin('mill_order o','o.id=s.order_id')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->order('s.id desc')
            ->paginate()
            ->each(function ($v){

                //样品
                $v['sample_sort'] = '';
                $v['sample_name'] = '';
                $v['sample_spec'] = '';
                $v['sample_num'] = '';
                $v['sample_color'] = '';
                $v['sample_supplier'] = '';
                $v['sample_date'] = '';
                $v['sample'] = json_decode($v['sample'],true);
                if(!empty($v['sample'])){
                    foreach ($v['sample'] as $sak=>$sav) {

                        //if(empty($sav['note']))$sav['note'] = "&nbsp;";
                        $v['sample_sort'] .= "<div style='border-bottom: 1px solid;'>{$sav['sort']}</div>";
                        $v['sample_name'] .= "<div style='border-bottom: 1px solid;'>{$sav['name']}</div>";
                        $v['sample_spec'] .= "<div style='border-bottom: 1px solid;'>{$sav['spec']}</div>";
                        $v['sample_num'] .= "<div style='border-bottom: 1px solid;'>{$sav['num']}</div>";
                        $v['sample_color'] .= "<div style='border-bottom: 1px solid;'>{$sav['color']}</div>";
                        $v['sample_supplier'] .= "<div style='border-bottom: 1px solid;'>{$sav['supplier']}</div>";
                        $v['sample_date'] .= "<div style='border-bottom: 1px solid;'>{$sav['date']}</div>";
                    }
                }

                //要求
                $require = '';
                $v['require'] = json_decode($v['require'],true);
                if(!empty($v['require'])){
                    foreach ($v['require'] as $rk=>$rv_arr) {
                        $require .= "{$rk}：" . implode(',', $rv_arr) . "</br>";
                    }
                    $v['require'] = $require;
                }

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">样品编号</th>\' +
                        \'<th colspan="1">客户公司</th>\' +
                        \'<th colspan="1">工程名称</th>\' +
                        \'<th colspan="7">样品</th>\' +
                        \'<th colspan="1">要求</th>\' +
                        \'<th colspan="1">状态</th>\' +
                        \'<th colspan="1" class="disable-dch">操作</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    right_height = parseInt(right_height) + 50;
                    $("#builder-table-right").css("height",right_height+"px");
                            
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('样品管理（样品数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order_sample') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 's.company', '客户公司','like'],
                ['text:2', 's.engineering', '工程名称', 'like'],
                ['daterange:2', 's.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['sample_sn', ''],
                ['company', ''],
                ['engineering', ''],
                ['sample_sort', '序号'],
                ['sample_name', '品名'],
                ['sample_spec', '规格及材质'],
                ['sample_num', '数量'],
                ['sample_color', '颜色/编号'],
                ['sample_supplier', '指定涂料厂家'],
                ['sample_date', '交货时间要求'],
                ['require', ''],
                ['status','','callback',function($value, $data){
                    //复审
                    $text = '';
                    $note = $data['status_note'];
                    if($data['again_status'] != 1){
                        $value = $data['again_status'];
                        $text = '复审';
                        $note = $data['again_status_note'];
                    }
                    $status = OrderModel::status_tag($value,$text.SampleModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$note.'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '', 'btn']
            ])
            ->addTopButtons(['add' => ['title' => '新增','class'=>'btn btn-primary','href'=>url('add',['order_id'=>$order_id]), 'icon' => 'fa fa-plus-circle']]) // 批量添加顶部按钮
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->addRightButton('show',['title' => '样品预览','href' => url('show2',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['样品预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('prints',['title' => '打印','href' => admin_url('prints',['id'=>'__id__']),'class'=>'btn btn-primary','icon'=>'','target'=>'_blank'])
            ->addRightButton('again',['title' => '申请修改','href' => admin_url('again',['id'=>'__id__']),'class'=>'btn btn-default ajax-get confirm','icon'=>''])
            ->addRightButton('progress',['title' => '进度','href' => url('progress',['id' => '__id__']),'class'=>'btn btn-primary','icon'=>''],['area' => ['50%', '90%'], 'title' => ['进度', 'font-size:24px;text-align: center;']])
            //->replaceRightButton(['status'=>['not in','1'],'','edit'])
            ->replaceRightButton(['status' => ['>','1']],'',['edit'])
            ->replaceRightButton(['again_status' => ['<>','1']],'',['again'])
            ->replaceRightButton(['status' => ['<>','2']],'',['prints','again','progress'])
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'sample'  => 600,
                'require'  => 200,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $id = input('id');
        $order_id = input('order_id');

        if ($this->request->isPost()) {
            $data = input();
            unset($data['__token__']);
            unset($data['image_test']);

            if(empty($data['sample']['sort']))$this->error('请填写样品');

            foreach ($data['require'] as $rk=>$rv){
                foreach ($rv as &$rvv){
                    if(strpos($rvv,'input') !== false){
                        $val = $data['require_input'][$rk][$rvv];
                        $rvv = str_replace("input",$val,$rvv);
                    }
                }
                $data['require'][$rk] = $rv;
            }

            $data['sample'] = json_encode(SampleModel::serialize($data['sample']),JSON_UNESCAPED_UNICODE);
            $data['require'] = json_encode($data['require'],JSON_UNESCAPED_UNICODE);
            $data['status'] = 1;
            $data['create_time'] = time();
            $data['update_time'] = time();

            $order_update = [
                'engineering'      =>  $data['engineering'],
            ];

            //unset($data['engineering']);
            unset($data['require_input']);

            if(!empty($id)){
                $data['id'] = $id;
                unset($data['create_time']);
                $re = SampleModel::update($data);
            }
            else $re = SampleModel::create($data);
            if ($re) {

                if(!empty($data['order_id']))Db::name('mill_order')->where(['order_pid'=>$data['order_id']])->update($order_update);

                $id = $re['id'];
                //$this->success('操作成功', admin_url('prints',['id'=>$id]) ,'_blank');
                $this->success('操作成功', cookie('__forward__'));
            }
            $this->error('操作失败');
        }

        if(!empty($id)){
            $order = Db::name('mill_order_sample')
                ->alias('s')
                ->field('s.*')
                ->where(['s.id'=>$id])
                ->find();
            if($order['order_id']){
                $order = Db::name('mill_order_sample')
                    ->alias('s')
                    ->field('o.*,c.company,c.sales,s.id,s.order_id,s.sample_sn,s.status_verify_uid,s.admin_uid,s.sample,s.content,s.require,s.note,s.type,s.order_num')
                    ->leftJoin('mill_order o','o.id=s.order_id')
                    ->leftJoin('mill_client c','c.id=o.client_id')
                    ->where(['s.id'=>$id])
                    ->find();
            }

            $order['sample'] = json_decode($order['sample'],true);
            $order['require'] = json_decode($order['require'],true);
            $order['sample_date'] = date('Y-m-d',$order['create_time']);
            $order['admin_nickname'] = get_nickname($order['admin_uid']);
            $order['verify_nickname'] = is_numeric($order['status_verify_uid'])?get_nickname($order['status_verify_uid']):'';
        }
        else{
            if($order_id){
                $order = Db::name('mill_order')
                    ->alias('o')
                    ->field('o.*,o.id as order_id,c.company,c.sales')
                    ->leftJoin('mill_client c','c.id=o.client_id')
                    ->where(['o.id'=>$order_id])
                    ->find();
            }
            else{
                $order['order_id'] = $order_id;
                $order['engineering'] = '';
                $order['company'] = '';
                $order['note'] = '';
                $order['sales'] = '';
            }

            $order['sample_date'] = date('Y-m-d',time());

            $start_time = strtotime(date('Y-m'));
            $last_sample = Db::name('mill_order_sample')->where("create_time >= {$start_time}")->count();
            $last_sample = intval($last_sample)+1;
            $order['sample_sn'] = date('Y-m')."-{$last_sample}";
            $order['pay_order'] = '';
            $order['type'] = 0;
            $order['sample'][] = [
                'sort'  =>'',
                'name'  =>'',
                'spec'  =>'',
                'num'   =>'',
                'color' =>'',
                'supplier'  =>'',
                'date'  =>'',
            ];

            $order['id'] = '';
            $order['content'] = '';
            $order['order_num'] = '';
            $order['image'] = '';
            $order['create_time'] = time();
            $order['update_time'] = time();
            $order['admin_nickname'] = get_nickname(UID);
            $order['admin_uid'] = UID;
            $order['verify_nickname'] = '';
        }

        $table_arr = SampleModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        //js
        $js = '<script type="text/javascript">

//$(\'#dch_image\').html($(\'#form_group_image\').find(\'.js-upload-image\').html());
                //删除
                function sample_del(obj) {
                    var length = $(".sample_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    console.log($(this).text());
                    $(obj).parent().parent().remove();
                }
                //新增
                function sample_add(obj) {
                    var add = $(".sample").parent().parent().html();
                    add = "<tr>"+add+"</tr>";
                      
                    $(add).insertAfter($(".sample").parent("td").parent("tr:last"));
                }
                //样品类型点击事件
                $("input[name=\'type\']").click(function(){
                    //样品类型
                    var type = $(this).val();
                    //部门签字
                    var gourp_type_div1 = "钣金生产部：";
                    var gourp_type_div2 = "喷涂部生产部：";
                    var gourp_type_div = "";
                    //获取样品编号
                    var sample_sn = $("input[name=\'sample_sn\']").val();
                    sample_sn = sample_sn.replace("YP","");
                    if(type == 1){
                        gourp_type_div1 = "设计部：";
                        gourp_type_div2 = "";
                        gourp_type_div = "";
                        sample_sn = "YP"+sample_sn;
                    }
                    //更新样品编号
                    $("input[name=\'sample_sn\']").val(sample_sn);
                    $("#sample_sn").text(sample_sn);
                    //更新部门
                    $("#gourp_type_div1").text(gourp_type_div1);
                    $("#gourp_type_div2").text(gourp_type_div2);
                    $("#gourp_type_div").text(gourp_type_div);
                })
            </script>';

        $info = $order;
        return ZBuilder::make('form')
            ->setPageTitle('打印样品') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['radio:12', 'type', '样品类型','', [0=>'普通',1=>'大样'],$info['type']],
                ['image:12', 'image_test', '样品图','','','','','hidden'],
            ])
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'sample', '', $table_data, $table_head],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 编辑
     * @param null $id
     * @return mixed
     */
    public function edit($id=null)
    {
        return $this->add();
    }
    /**
     * 打印
     * @return mixed
     */
    public function prints()
    {

        $id = input('param.id');

        $data = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*,o.engineering,o.create_time as sample_date,c.company,c.sales')
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['s.id'=>$id])
            ->find();
        $data['sample_date'] = date('Y-m-d',$data['create_time']);
        $data['sample'] = json_decode($data['sample'],true);
        $data['require'] = json_decode($data['require'],true);
        $data['admin_nickname'] = get_nickname($data['admin_uid']);
        $data['verify_nickname'] = is_numeric($data['status_verify_uid'])?get_nickname($data['status_verify_uid']):'';

        $html = SampleModel::toHtml($data);

        $html = "<div style='width: 21cm;'>{$html}</div>";

        exit($html);
    }
    /**
     * 进度
     * @return mixed
     */
    public function progress()
    {
        $id = input('id');

        if ($this->request->isPost()) {
            $data = input();
            unset($data['__token__']);

            $data['id'] = $id;
            $re = SampleModel::update($data);
            //关闭子窗口，并刷新父窗口
            if($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        $order = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*')
            ->where(['s.id'=>$id])
            ->find();

        $info = $order;
        return ZBuilder::make('form')
            ->setPageTitle('进度') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['static:12', 'sample_sn', '样品编号'],
                ['radio:12', 'progress', '进度','', SampleModel::$progress,$info['progress']],
                ['text:12', 'address_sn', '发货单号'],
            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 待审核工程列表页
     * @return mixed
     */
    public function examine()
    {

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['s.status','in','-1,1'];

        //待审核
        $map0[] = ['s.status','eq','1'];
        $total0 = Db::name('mill_order_sample')
            ->alias('s')
            ->where($map0)
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->count();
        //未通过
        $map01[] = ['s.status','eq','-1'];
        $total01 = Db::name('mill_order_sample')
            ->alias('s')
            ->where($map01)
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->count();

        // 数据列表
        $data_list = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*')
            ->where($map)
            //->leftJoin('mill_order o','o.id=s.order_id')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->order('s.id desc')
            ->paginate()
            ->each(function ($v){

                //样品
                $v['sample_sort'] = '';
                $v['sample_name'] = '';
                $v['sample_spec'] = '';
                $v['sample_num'] = '';
                $v['sample_color'] = '';
                $v['sample_supplier'] = '';
                $v['sample_date'] = '';
                $v['sample'] = json_decode($v['sample'],true);
                if(!empty($v['sample'])){
                    foreach ($v['sample'] as $sak=>$sav) {

                        //if(empty($sav['note']))$sav['note'] = "&nbsp;";
                        $v['sample_sort'] .= "<div style='border-bottom: 1px solid;'>{$sav['sort']}</div>";
                        $v['sample_name'] .= "<div style='border-bottom: 1px solid;'>{$sav['name']}</div>";
                        $v['sample_spec'] .= "<div style='border-bottom: 1px solid;'>{$sav['spec']}</div>";
                        $v['sample_num'] .= "<div style='border-bottom: 1px solid;'>{$sav['num']}</div>";
                        $v['sample_color'] .= "<div style='border-bottom: 1px solid;'>{$sav['color']}</div>";
                        $v['sample_supplier'] .= "<div style='border-bottom: 1px solid;'>{$sav['supplier']}</div>";
                        $v['sample_date'] .= "<div style='border-bottom: 1px solid;'>{$sav['date']}</div>";
                    }
                }

                //要求
                $require = '';
                $v['require'] = json_decode($v['require'],true);
                if(!empty($v['require'])){
                    foreach ($v['require'] as $rk=>$rv_arr) {
                        $require .= "{$rk}：" . implode(',', $rv_arr) . "</br>";
                    }
                    $v['require'] = $require;
                }

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">样品编号</th>\' +
                        \'<th colspan="1">客户公司</th>\' +
                        \'<th colspan="1">工程名称</th>\' +
                        \'<th colspan="7">样品</th>\' +
                        \'<th colspan="1">要求</th>\' +
                        \'<th colspan="1">状态</th>\' +
                        \'<th colspan="1" class="disable-dch">操作</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    right_height = parseInt(right_height) + 50;
                    $("#builder-table-right").css("height",right_height+"px");
                            
                })
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("样品审核（待审核{$total0}/未通过{$total01}）") // 页面标题
            ->setTableName('mill_order_sample') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 's.company', '客户公司','like'],
                ['text:2', 's.engineering', '工程名称', 'like'],
                ['daterange:2', 's.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['sample_sn', ''],
                ['company', ''],
                ['engineering', ''],
                ['sample_sort', '序号'],
                ['sample_name', '品名'],
                ['sample_spec', '规格及材质'],
                ['sample_num', '数量'],
                ['sample_color', '颜色/编号'],
                ['sample_supplier', '指定涂料厂家'],
                ['sample_date', '交货时间要求'],
                ['require', ''],
                ['status','','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,SampleModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '', 'btn']
            ])
            ->addRightButton('show',['title' => '样品预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['样品预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|2",'icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '2']], '', 'enable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'sample'  => 600,
                'require'  => 200,
            ])
            ->fetch(); // 渲染模板


    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv_arr = explode('@',$fieldv);
        foreach ($fieldv_arr as $v){

            $v = explode('|',$v);
            if (false === SampleModel::where('id', $id)->setField($v[0], $v[1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            //审核人员
            SampleModel::where('id', $id)->setField($v[0].'_verify_uid', UID);
            //审核时间
            SampleModel::where('id', $id)->setField($v[0].'_time', time());
        }

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === SampleModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))SampleModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            SampleModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }
    /**
     * 申请修改
     */
    public function again()
    {

        $id = input('param.id');

        $where = ['id'=>$id];

        $sample_sn = Db::name('mill_order_sample')->where($where)->value('sample_sn');
        $model = 'mill_order_sample';
        $remark = "操作人员：".get_nickname(UID)."，申请修改样品单，样品编号：{$sample_sn}";

        LogModel::addLog($id,$model,1,$remark);

        $add = [
            'again_status'  =>  0,
        ];
        Db::name('mill_order_sample')->where($where)->update($add);

        $this->success('提交成功');
    }
    /**
     * 申请修改列表页
     * @return mixed
     */
    public function againList()
    {

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['s.again_status','in','-1,0'];

        //待审核
        $map0[] = ['s.again_status','eq','0'];
        $total0 = Db::name('mill_order_sample')
            ->alias('s')
            ->where($map0)
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->count();
        //未通过
        $map01[] = ['s.again_status','eq','-1'];
        $total01 = Db::name('mill_order_sample')
            ->alias('s')
            ->where($map01)
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->count();

        // 数据列表
        $data_list = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*')
            ->where($map)
            //->leftJoin('mill_order o','o.id=s.order_id')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->order('s.id desc')
            ->paginate()
            ->each(function ($v){

                //样品
                $v['sample_sort'] = '';
                $v['sample_name'] = '';
                $v['sample_spec'] = '';
                $v['sample_num'] = '';
                $v['sample_color'] = '';
                $v['sample_supplier'] = '';
                $v['sample_date'] = '';
                $v['sample'] = json_decode($v['sample'],true);
                if(!empty($v['sample'])){
                    foreach ($v['sample'] as $sak=>$sav) {

                        //if(empty($sav['note']))$sav['note'] = "&nbsp;";
                        $v['sample_sort'] .= "<div style='border-bottom: 1px solid;'>{$sav['sort']}</div>";
                        $v['sample_name'] .= "<div style='border-bottom: 1px solid;'>{$sav['name']}</div>";
                        $v['sample_spec'] .= "<div style='border-bottom: 1px solid;'>{$sav['spec']}</div>";
                        $v['sample_num'] .= "<div style='border-bottom: 1px solid;'>{$sav['num']}</div>";
                        $v['sample_color'] .= "<div style='border-bottom: 1px solid;'>{$sav['color']}</div>";
                        $v['sample_supplier'] .= "<div style='border-bottom: 1px solid;'>{$sav['supplier']}</div>";
                        $v['sample_date'] .= "<div style='border-bottom: 1px solid;'>{$sav['date']}</div>";
                    }
                }

                //要求
                $require = '';
                $v['require'] = json_decode($v['require'],true);
                if(!empty($v['require'])){
                    foreach ($v['require'] as $rk=>$rv_arr) {
                        $require .= "{$rk}：" . implode(',', $rv_arr) . "</br>";
                    }
                    $v['require'] = $require;
                }

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">样品编号</th>\' +
                        \'<th colspan="1">客户公司</th>\' +
                        \'<th colspan="1">工程名称</th>\' +
                        \'<th colspan="7">样品</th>\' +
                        \'<th colspan="1">要求</th>\' +
                        \'<th colspan="1">状态</th>\' +
                        \'<th colspan="1" class="disable-dch">操作</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    right_height = parseInt(right_height) + 50;
                    $("#builder-table-right").css("height",right_height+"px");
                            
                })
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("样品审核（待审核{$total0}/未通过{$total01}）") // 页面标题
            ->setTableName('mill_order_sample') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 's.company', '客户公司','like'],
                ['text:2', 's.engineering', '工程名称', 'like'],
                ['daterange:2', 's.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['sample_sn', ''],
                ['company', ''],
                ['engineering', ''],
                ['sample_sort', '序号'],
                ['sample_name', '品名'],
                ['sample_spec', '规格及材质'],
                ['sample_num', '数量'],
                ['sample_color', '颜色/编号'],
                ['sample_supplier', '指定涂料厂家'],
                ['sample_date', '交货时间要求'],
                ['require', ''],
                ['again_status','','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['again_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '', 'btn']
            ])
            ->addRightButton('show',['title' => '样品预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['样品预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('enable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=again_status|1@status|0",'icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'again_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['again_status' => ['in', '1']], '', 'enable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'sample'  => 600,
                'require'  => 200,
            ])
            ->fetch(); // 渲染模板


    }
    /**
     * 样品浏览
     * @return mixed
     */
    public function show()
    {

        $id = input('param.id');

        $data = Db::name('mill_order_sample')
            ->alias('s')
            ->field('s.*,o.engineering,o.create_time as sample_date,c.company,c.sales')
            ->leftJoin('mill_order o','o.id=s.order_id')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where(['s.id'=>$id])
            ->find();
        $data['sample_date'] = date('Y-m-d',$data['create_time']);
        $data['sample'] = json_decode($data['sample'],true);
        $data['require'] = json_decode($data['require'],true);
        $data['admin_nickname'] = get_nickname(UID);
        $data['verify_nickname'] = is_numeric($data['status_verify_uid'])?get_nickname($data['status_verify_uid']):'';

        $html = SampleModel::toHtml($data);

        $html = str_replace('window.print();',"",$html);

        exit($html);

    }
    public function show2()
    {
        return $this->show();
    }

}
